#!/usr/bin/env python
import sys, math, random
import src.crop as cr
from mpi4py import MPI
import numpy as np
from util import Timer


comm = MPI.COMM_WORLD
p = comm.size
rank = comm.rank
root = 0

crop = cr.CRoP(0.1, rank, p)
with Timer() as t :
	if rank == 0 :
		#A = B = np.load('stoc_mat_1000.npy',mmap_mode='r')
		A = B = np.load('../data/np_mat__10000_0.001.npy',mmap_mode='r')
#		A = B = np.memmap('stoc_mat_1000.npy',dtype="double", mode='r', shape=(1000,1000))
		print "nnz ", np.count_nonzero(A)
		n = 0
		while n < len(A[0]) :
			data = ([np.array(A.T[n,:]),MPI.DOUBLE], [np.array(B[n,:]),MPI.DOUBLE])
			comm.bcast(data, root)
			crop.crop(data[0][0], data[1][0])
			n += 1
		comm.bcast("Done", root)
	else :
		print "proc: ", rank
		data = ""
		done = False
		while not done :
			data = comm.bcast(data, root)
			if data != "Done" :
				crop.crop(data[0][0], data[1][0])
			else :
				done = True

summary = crop.get_dist()
data = comm.gather(summary, root)
if rank == root :
	print "%s\t%.03f\tmaster" % (t.interval,rank)
#	for i in range(p) :
#		print data[i]
print "%s\t%.03f\t" % (t.interval,rank)